from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.core.mail import send_mail


# Create your views here.
# todo  定时 邮件

def index(request):
    return HttpResponse('index')


def testpost(request):
    if request.method == "GET":
        return render(request, 'testpost.html')
    if request.method == "POST":
        wd = request.POST.get("wd", "")
        print(wd)
        return HttpResponse('ok')


from .models import Gitinfo


def info(request):
    if request.method == "GET":
        return render(request, 'info.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        gitaddr = request.POST.get("gitaddr", "")
        cls = request.POST.get("cls", "")

        # gitinfo = Gitinfo(name=name,
        #                   gitaddr=gitaddr,
        #                   classblong_id=1
        #                   )
        gitinfo = Gitinfo(name=name,
                          gitaddr=gitaddr
                          )
        gitinfo.save()
        return HttpResponse("ok")


from gitcollecttable import settings
import os
import time


def genpicname(filename):
    """
    根据一个名称  xx.jpg 生成一个唯一的新的文件名
    :param filename:
    :return:
    """
    prefix, suffix = filename.rsplit('.', maxsplit=1)

    bfilename = (prefix + str(time.time())).encode('utf-8')

    return md5(bfilename).hexdigest() + "." + suffix


def saveicon(iconfile):
    """
    根据iconfile保存文件到 static/img 路径下
    :param iconfile:
    :return: 文件的名称
    """
    save_path = os.path.join(settings.BASE_DIR, 'static', 'img')
    # filename = iconfile.name.split('.')[0] + str(time.time()).split('.')[0] + "." + iconfile.name.split('.')[1]
    filename = genpicname(iconfile.name)
    with open(os.path.join(save_path, filename), 'wb') as f:
        for chunk in iconfile.chunks():
            f.write(chunk)

    return filename


from hashlib import md5

from .models import Teacher


def teacher(request):
    if request.method == "GET":
        return render(request, 'teacher.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        jobtype = request.POST.get("jobtype", "")
        salary = request.POST.get("salary", "")
        phone = request.POST.get("phone", "")
        icon_file = request.FILES.get("icon", "")

        icon_name = saveicon(icon_file)

        introduction = request.POST.get("introduction", "")

        t1 = Teacher(
            name=name,
            jobtype=jobtype,
            salary=salary,
            phone=phone,
            icon=icon_name,
            introduction=introduction
        )

        # 获取icon 保存icon 存储路径
        t1.save()

        return HttpResponse('teacher')


def showteacher(request, teacherid):
    t1 = Teacher.objects.get(pk=teacherid)

    return render(request, 'showteacher.html', {"teacher": t1})